package com.weetop.aklyscan.activity.sreach;

import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonRecyclerAdapter;
import com.honeywell.aidc.AidcManager;
import com.honeywell.aidc.BarcodeFailureEvent;
import com.honeywell.aidc.BarcodeReadEvent;
import com.honeywell.aidc.BarcodeReader;
import com.honeywell.aidc.TriggerStateChangeEvent;
import com.weetop.aklyscan.R;
import com.weetop.aklyscan.base.BaseActivity;
import com.weetop.aklyscan.base.BaseUrl;
import com.weetop.aklyscan.base.mvp.BaseModel;
import com.weetop.aklyscan.bean.SearchBean;
import com.weetop.aklyscan.bean.SearchItemBean;
import com.weetop.aklyscan.bean.SerailBean;
import com.weetop.aklyscan.bean.SerailBean1;
import com.weetop.aklyscan.presenter.LocationSearchPresent;
import com.weetop.aklyscan.utils.BaseUtils;
import com.weetop.aklyscan.view.LocationSearchView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cc.shinichi.library.tool.utility.ui.ToastUtil;

public class SearchPositionActivity4 extends BaseActivity<LocationSearchPresent> implements LocationSearchView, BarcodeReader.BarcodeListener,
        BarcodeReader.TriggerListener {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.number)
    TextView number;
    @BindView(R.id.chaxun)
    TextView chaxun;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private ArrayList<SearchBean.DataBean> data = new ArrayList<>();
    private CommonRecyclerAdapter<SearchBean.DataBean> adapter;
    private boolean isRefresh, isLoadMore;
    private int page = 1;
    private String keywords = "";
    private String goodsType = "1";

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                text.setText((String) msg.obj);
                text.setBackgroundResource(R.drawable.et_grey);
            }
        }
    };



    @Override
    public void getserailSuccess(BaseModel<SearchBean> o) {
        try {
            SearchBean serailBean = o.getData();
            data.clear();
            adapter.clear();

            data.addAll(serailBean.getList_data());
            adapter.addAll(serailBean.getList_data());
            int count = 0;
            for (SearchBean.DataBean dataBean :
                    serailBean.getList_data()) {
                count += (dataBean.getCk_count_num() + dataBean.getRk_count_num());
            }
            number.setText(count + "");
//            playRing("shujuyouxiao.mp3");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    protected LocationSearchPresent createPresenter() {
        return new LocationSearchPresent(this, this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_position4);
        ButterKnife.bind(this);

        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new CommonRecyclerAdapter<SearchBean.DataBean>(mActivity, R.layout.item_search4, data) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, SearchBean.DataBean item, int position) {
                helper.setText(R.id.tv_xuhao, position + 1 + "");
                helper.setText(R.id.sn, item.getMatter_code());
                helper.setText(R.id.model, item.getMatter_name());
                helper.setText(R.id.name, item.getOrder_sn());
                helper.setText(R.id.code, String.valueOf(item.getCk_count_num()+item.getRk_count_num()));
            }
        };
        recyclerView.setAdapter(adapter);
        initScan();

//        Message message = new Message();
//        message.what = 1;
//        message.obj = "PJCG202108200001";
//        handler.sendMessage(message);
    }

    @OnClick({R.id.iv_back, R.id.qingkong, R.id.chaxun})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                if (BaseUtils.fastClick()) {
                    finish();
                }
                break;
            case R.id.qingkong:
                text.setText("");
                text.setBackgroundResource(R.drawable.et_yellow);
                number.setText("");
                data.clear();
                adapter.clear();
                break;
            case R.id.chaxun:
                if (TextUtils.isEmpty(text.getText().toString().trim())) {
                    ToastUtil.getInstance()._short(SearchPositionActivity4.this, "凭证编号不能为空");
                    return;
                }
                mPresenter.Into61(text.getText().toString().trim(), "3", "");
                break;
        }
    }

    AidcManager manager;
    BarcodeReader barcodeReader;

    private void initScan() {
        //第一步：获取扫描资源，设置扫描参数，开启扫描功能
        AidcManager.create(this, new AidcManager.CreatedCallback() {
            @Override
            public void onCreated(AidcManager aidcManager) {
                manager = aidcManager;
                barcodeReader = manager.createBarcodeReader();
                try {
                    //设置扫描参数
//                    barcodeReader.setProperty(BarcodeReader.PROPERTY_CODE_128_ENABLED, true); //开启Code128码制
//                    barcodeReader.setProperty(BarcodeReader.PROPERTY_EAN_13_ENABLED, false); //关闭EAN13码制
//                    barcodeReader.setProperty(BarcodeReader.PROPERTY_TRIGGER_CONTROL_MODE, BarcodeReader.TRIGGER_CONTROL_MODE_CLIENT_CONTROL); //设置手动触发模式

                    barcodeReader.claim(); //开启扫描功能
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //第二步：添加侧面扫描键事件监听和条码事件监听
                barcodeReader.addTriggerListener(SearchPositionActivity4.this);
                barcodeReader.addBarcodeListener(SearchPositionActivity4.this);
            }
        });
    }

    @Override
    public void onBarcodeEvent(BarcodeReadEvent barcodeReadEvent) {
        String barcodeData = barcodeReadEvent.getBarcodeData();
        System.out.println("扫描结果：" + barcodeData);
        Message message = new Message();
        message.what = 1;
        message.obj = barcodeData;
        handler.sendMessage(message);
    }

    @Override
    public void onFailureEvent(BarcodeFailureEvent barcodeFailureEvent) {
        System.out.println("失败：");

    }

    @Override
    public void onTriggerEvent(TriggerStateChangeEvent triggerStateChangeEvent) {
        System.out.println("按键：");
        if (triggerStateChangeEvent.getState() == true) {
            try {
                barcodeReader.light(true);        //开启补光
                barcodeReader.aim(true);        //开启瞄准线
                barcodeReader.decode(true);        //开启解码
            } catch (Exception e) {
                Toast.makeText(this, "开启扫描失败", Toast.LENGTH_SHORT).show();
            }
        } else if (triggerStateChangeEvent.getState() == false) {
            try {
                barcodeReader.light(false);        //关闭补光
                barcodeReader.aim(false);        //关闭瞄准线
                barcodeReader.decode(false);    //关闭解码
            } catch (Exception e) {
                Toast.makeText(this, "关闭扫描失败", Toast.LENGTH_SHORT).show();
            }
        }
    }


    private AssetManager assetManager;
    private MediaPlayer player = new MediaPlayer();

    private void playRing(String fileName) {
        try {
            assetManager = getAssets();
            AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);
//            if (player.isPlaying()) {
            player.reset();
//            }
            player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            player.prepare();
            player.start();
            player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    player.stop();
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void playUrl(String fileName, final int i) {
        if (TextUtils.isEmpty(fileName)) {
            if (i == 1) {
                playRing("luruchenggong.mp3");
                return;
            } else {
                playRing("wuxiao.mp3");
                return;
            }
        }
        try {
            player.reset();
            if (!fileName.contains("http")) {
                player.setDataSource(BaseUrl.mp3Url + fileName);
            } else {
                player.setDataSource(fileName);
            }
            player.prepare();
            player.start();
            player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    if (i == 1) {
                        playRing("luruchenggong.mp3");
                    } else {
                        playRing("wuxiao.mp3");
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (barcodeReader != null) {
            try {
                barcodeReader.claim();        //开启扫描功能
            } catch (Exception e) {
                Toast.makeText(this, "开启扫描失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (barcodeReader != null) {
            barcodeReader.release();        //释放扫描资源
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (barcodeReader != null) {
            barcodeReader.removeBarcodeListener(this);
            barcodeReader.removeTriggerListener(this);
            barcodeReader.close();
        }
        if (manager != null) {
            manager.close();
        }
    }
}
